package edu.office.applicationRepository;

import edu.office.entities.Edgeamongknowledge;
import edu.office.entities.Knowledge;
import edu.office.entities.Learningresource;
import edu.office.entities.Subject;
import edu.office.tools.*;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.inject.Named;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Named("learningresourceRepositoryA")
@ApplicationScoped
public class LearningresourceRepository extends ApplicationCommonRepository<Learningresource> {

    public final static int MAXPICTURENUMBER = 5;
     final int maxVideoSize = 1024 * 1000 * 500;
     final int maxAudioSize = 1024 * 1000 * 100;
     final int maxSize = 1024000;
     final int maxPDFSize = 10240000;
    @Inject
     KnowledgeRepository knowledgeRepository;
    @Inject
    PersonalSessionSetup personalSessionSetup;
    private List<Learningresource> learningResourceList = null;

    public LearningresourceRepository() {
    }

    public int getMaxVideoSize() {
        return maxVideoSize;
    }

    public int getMaxAudioSize() {
        return maxAudioSize;
    }

    public int getMaxPDFSize() {
        return maxPDFSize;
    }

    public int getMaxSize() {
        return maxSize;
    }

    public List<Learningresource> getLearningResourceList4Subject(Subject subjectId) {
        learningResourceList = new LinkedList<>();
        knowledgeRepository.getKnowledgeList4Subject(subjectId).forEach((knowledge) -> learningResourceList.addAll(find("KNOWLEDGE_ID",knowledge.getID()).list()));
        return learningResourceList;
    }

    public String pictureValidate(Part file) {
        if (null != file) {
            if (file.getContentType().contains("image")) {
                if (file.getSize() > getMaxSize()) {
                return   EOMessage.getEOMessageENUM(EOMessage1.Too_Big);
                }
            } else {
               return EOMessage.getEOMessageENUM(EOMessage1.Not_Image);
            }
        }
        return "";
    }

    public Map<String, String> getVideos(Knowledge knowledge) {
        Map<String, String> map = new HashMap<>();
        Learningresource learningresources =
                find("KNOWLEDGE_ID=?1 and TYPE=?2", knowledge.getID(), StaticFields.VIDEOTYPE).firstResult();

            if (learningresources.getVALUEINFO().contains(",")) {
                String[] videos = learningresources.getVALUEINFO().split(",");
                for (String str : videos) {
                    map.put(str.substring(0, str.indexOf("#")), str.substring(str.indexOf("#") + 1));
                }
                return map;
            } else {
                String video = learningresources.getVALUEINFO();
                map.put(video.substring(0, video.indexOf("#")), video.substring(video.indexOf("#") + 1));
                return map;
            }
    }

    public String[] getAIPfileNames(int fileType, Knowledge knowledge) {
        Learningresource learningresource =
                find("KNOWLEDGE_ID=?1 and TYPE=?2", knowledge.getID(), fileType).firstResult();
        if (null != learningresource.getID()) {
            if (learningresource.getVALUEINFO().contains(",")) {
                return learningresource.getVALUEINFO().split(",");
            } else {
                return new String[]{learningresource.getVALUEINFO()};
            }
        } else {
            return new String[0];
        }
    }

    //下面3个方法用来控制页面显示哪些添加按钮，在添加音频的页面上，不再显示添加音频，其他类似
    public boolean notAudio(Map.Entry<Integer, String> resource) {
        return resource.getKey() != StaticFields.AUDIOTYPE;
    }

    public boolean notPDF(Map.Entry<Integer, String> resource) {
        return resource.getKey() != StaticFields.PDFTYPE;
    }

    public boolean notImage(Map.Entry<Integer, String> resource) {
        return resource.getKey() != StaticFields.IMAGETYPE;
    }

    public boolean notVideo(Map.Entry<Integer, String> resource) {
        return resource.getKey() != StaticFields.VIDEOTYPE;
    }

    public void createLearningResource4Knowledge(Knowledge knowledge, Part[] parts, int fileType) {
        createLearningResource(true, null, knowledge, parts, fileType);
    }

    public void createLearningResource4EdgeAmongKnowledge(Edgeamongknowledge edgeamongknowledge, Part[] parts, int fileType) {
        createLearningResource(false, edgeamongknowledge, null, parts, fileType);
    }

    private void createLearningResource(boolean is4knowledge, Edgeamongknowledge edgeamongknowledge, Knowledge knowledge, Part[] parts, int fileType) {
        for (Part p : parts) {
            int size = 0;
            if (p != null) {
                // boolean fileExist = true;
                //首先判断当前知识点下是否有此类资源
                List<Learningresource> learningresources;
                if (is4knowledge) {
                    learningresources = find("select * from learningresource where knowledge_id=" + knowledge.getID() + " and type=" + fileType).firstResult();
                } else {
                    learningresources = find("select * from learningresource where edgeAmongKnowledge_id=" + edgeamongknowledge.getID() + " and type=" + fileType).firstResult();
                }
                if (learningresources.isEmpty()) {//没有此类资源
                    Learningresource ls = new Learningresource();
                    if (is4knowledge) {
                        ls.setKNOWLEDGE_ID(knowledge.getID());
                    } else {
                        ls.setEDGEAMONGKNOWLEDGE_ID(edgeamongknowledge.getID());
                    }
                    ls.setTYPE(fileType);
                    if (fileType == StaticFields.VIDEOTYPE) {
                        ls.setVALUEINFO(knowledge.getID() + "_" + size + "." + Tool.getExtension(p.getSubmittedFileName()) + "#" + p.getContentType());
                    } else {
                        ls.setVALUEINFO(knowledge.getID() + "_" + size + "." + Tool.getExtension(p.getSubmittedFileName()));
                    }
                    create(ls);
                } else {//已经存在此类资源
                    Learningresource ls1 = learningresources.get(0);
                    size = ls1.getVALUEINFO().split(",").length;
                    if (fileType == StaticFields.VIDEOTYPE) {
                        ls1.setVALUEINFO(ls1.getVALUEINFO() + "," + knowledge.getID() + "_" + size + "." + Tool.getExtension(p.getSubmittedFileName()) + "#" + p.getContentType());
                    } else {
                        ls1.setVALUEINFO(ls1.getVALUEINFO() + "," + knowledge.getID() + "_" + size + "." + Tool.getExtension(p.getSubmittedFileName()));
                    }
                }

                InputStream in;
                try {
                    in = p.getInputStream();
                    File file = new File(personalSessionSetup.getFilePath() + "/knowledgeResources" + "/" + getFoldName(fileType));
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    Files.copy(in, new File(personalSessionSetup.getFilePath() + "/knowledgeResources" + "/" + getFoldName(fileType) + "/" + knowledge.getID() + "_" + size + "." + Tool.getExtension(p.getSubmittedFileName())).toPath());
                } catch (IOException ex) {
                    System.out.println("上传文件出错");
                }
            }
        }
    }

    private String getFoldName(int type) {
        if (type == StaticFields.IMAGETYPE) {
            return StaticFields.IMAGE;
        }
        if (type == StaticFields.VIDEOTYPE) {
            return StaticFields.VIDEO;
        }
        if (type == StaticFields.AUDIOTYPE) {
            return StaticFields.AUDIO;
        }
        if (type == StaticFields.PDFTYPE) {
            return StaticFields.PDF;
        }
        return "";
    }

    public void deleteFiles(Knowledge knowledge1, int type, String... strs) {
        List<Learningresource> learningresources = list("select * from learningresource where knowledge_id=" + knowledge1.getID() + " and type=" + type);
        StringBuffer fileName;
        Learningresource learningresource = learningresources.get(0);//一定存在，因为已经在页面上显示出来了
        //取得当前资源的所有值
        String valueInfoStr = learningresource.getVALUEINFO();
        StringBuffer stringBuffer = new StringBuffer(valueInfoStr);
        if (strs.length == 1) {
            fileName = new StringBuffer(strs[0]);
        } else {
            fileName = new StringBuffer();
            for (String s : strs) {
                fileName.append(s);
            }
        }
        //找到前台传过来的值，从stringBuffer中删除掉,首先判断数据库中如果只有一个视频的话，则需要删除掉该条资源
        if (fileName.toString().contentEquals(stringBuffer)) {
            destroy(learningresource);
        } else {
            int index = stringBuffer.indexOf(fileName.toString());
            stringBuffer.delete(index, index + fileName.length() + 1);
            if (stringBuffer.charAt(stringBuffer.length() - 1) == ',') {
                stringBuffer.delete(stringBuffer.length() - 1, stringBuffer.length());
            }
            learningresource.setVALUEINFO(stringBuffer.toString());
        }
        if (fileName.toString().contains("#")) {
            fileName = new StringBuffer(fileName.substring(0, fileName.indexOf("#")));
        }
        //删除服务器中的文件
        File f = new File(personalSessionSetup.getFilePath() + "/knowledgeResources/" + getFoldName(type) + "/" + fileName);
        if (f.exists()) f.delete();
    }

    public int numberOfnewPicturePart(Learningresource lnrs) {
        String[] valueStrings;
        int uploadShowNumber = 0;
        Learningresource ls = new Learningresource();
        if (null != lnrs.getVALUEINFO()) {
            valueStrings = lnrs.getVALUEINFO().split(",");
            uploadShowNumber = MAXPICTURENUMBER - valueStrings.length;
        }
        //get the number of pictures and show them on Edit page
        //and less the number of pictures to be uploaded
        return uploadShowNumber;
    }

    public int numberOfnewFilePart(Learningresource lnrs, int fileType,Knowledge knowledge1) {
        String[] valueStrings;
        int uploadShowNumber;
        Learningresource currentN =new Learningresource();
        if (knowledge1 != null && knowledge1.getID() != null) {
            List<Learningresource> lrList = list("select * from learningresource where knowledge_id=" + knowledge1.getID() + " and type=" + fileType);
            if (lrList != null && !lrList.isEmpty()) {
                currentN=lrList.get(0);
            }
        }
        if (null != lnrs) {
            valueStrings = currentN.getVALUEINFO().split(",");
            uploadShowNumber = MAXPICTURENUMBER - valueStrings.length;
        } else {
            uploadShowNumber = MAXPICTURENUMBER;
        }
        //get the number of pictures and show them on Edit page
        //and less the number of pictures to be uploaded
        if (uploadShowNumber - 1 <= 0) {
            return 0;
        } else {
            Part[] filesPart = new Part[uploadShowNumber];
            return filesPart.length - 1;
        }
    }

    public void update(Part[] picturePart, Learningresource ls) {
        int i = 0;//上传图片的个数
        String valueInfoString="";
        for (Part part : picturePart) {
            if (null != part) {
                try (InputStream input = part.getInputStream()) {
                    String fileName = part.getSubmittedFileName();
                    File fold = new File(personalSessionSetup.getFilePath() + "/knowledgeResources" + "/" + ls.getKNOWLEDGE_ID());
                    if (!fold.exists()) {
                        fold.mkdir();
                    }
                    Files.copy(input, new File(personalSessionSetup.getFilePath() + "/knowledgeResources" + "/" + ls.getKNOWLEDGE_ID(), fileName).toPath());
                    valueInfoString = new StringBuilder().append(valueInfoString).append("," + fileName).toString();
                    i++;
                } catch (IOException e) {
                    System.out.println("LearningresourceController--update");
                }
            }

        }
        if (i > 0) {
            if (ls.getVALUEINFO().trim().isEmpty()) {
                valueInfoString = valueInfoString.substring(1);
            }
            ls.setVALUEINFO(ls.getVALUEINFO() + valueInfoString);
            valueInfoString = "";//restore the blank
            if (null == ls.getID()) {
                create(ls);
            }
        }
    }

    public String fileValidate(Object value, int fileType) {
        String msgs = "";
        Part file = (Part) value;
        if (null != value) {
            switch (fileType) {
                case StaticFields.IMAGETYPE:
                    if (!file.getContentType().contains(getFoldName(fileType))) {
                        return "Learningresource" + EOMessage.getEOMessageENUM(EOMessage1.Not_Image);
                    }
                    if (file.getSize() > getMaxSize()) {
                        return EOMessage.getEOMessageENUM(EOMessage1.Too_Big);
                    }
                case StaticFields.VIDEOTYPE:
                    if (!file.getContentType().contains(getFoldName(fileType))) {
                        return "Learningresource" + EOMessage.getEOMessageENUM(EOMessage1.Not_Video);
                    }
                    if (file.getSize() > getMaxVideoSize()) {
                        return EOMessage.getEOMessageENUM(EOMessage1.Too_Big);
                    }
                    break;
                case StaticFields.AUDIOTYPE:
                    if (!file.getContentType().contains(getFoldName(fileType))) {
                        return "Learningresource" + EOMessage.getEOMessageENUM(EOMessage1.Not_Audio);
                    }
                    if (file.getSize() > getMaxAudioSize()) {
                        return EOMessage.getEOMessageENUM(EOMessage1.Too_Big);
                    }
                case StaticFields.PDFTYPE:
                    if (!file.getContentType().contains(getFoldName(fileType))) {
                        return EOMessage.getEOMessageENUM(EOMessage1.Not_PDF);
                    }
                    if (file.getSize() > getMaxPDFSize()) {
                        return EOMessage.getEOMessageENUM(EOMessage1.Too_Big);
                    }
                    break;
            }
        }
        return EOMessage.getEOMessageENUM(EOMessage1.Succeed);
    }

    public boolean isExistImage(Knowledge knowledge1) {
        return getAIPfileNames(StaticFields.IMAGETYPE, knowledge1).length == 0 && knowledge1.getID() != null;
    }

    public boolean isExistImageFoot(Knowledge knowledge1) {
        return getAIPfileNames(StaticFields.IMAGETYPE, knowledge1).length > 0 && knowledge1.getID() != null;
    }

    public boolean isExistVideo(Knowledge knowledge1) {
        return getVideos(knowledge1).isEmpty() && knowledge1.getID() != null;
    }

    public boolean isExistVideoFoot(Knowledge knowledge1) {
        return getVideos(knowledge1).isEmpty() && knowledge1.getID() != null;
    }

    public boolean isExistAudio(Knowledge knowledge1) {
        return getAIPfileNames(StaticFields.AUDIOTYPE, knowledge1).length == 0 && knowledge1.getID() != null;
    }
}
